package com.imut.lagain.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imut.lagain.entity.MoodRecord;
import com.imut.lagain.service.IMoodRecordService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 心情记录控制器
 */
@RestController

@RequiredArgsConstructor
public class MoodRecordController {
    private static final Logger log = LoggerFactory.getLogger(MoodRecordController.class);
    
    private final IMoodRecordService moodRecordService;
    
    /**
     * 创建心情记录
     * @param moodRecord 心情记录信息
     * @return 创建结果
     */
    @PostMapping("/mood-records")
    public ResponseEntity<Map<String, Object>> createMoodRecord(@RequestBody MoodRecord moodRecord) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean success = moodRecordService.createMoodRecord(moodRecord);
            
            if (success) {
                response.put("success", true);
                response.put("message", "心情记录创建成功");
                response.put("data", moodRecord);
            } else {
                response.put("success", false);
                response.put("message", "心情记录创建失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("创建心情记录失败", e);
            response.put("success", false);
            response.put("message", "创建心情记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 更新心情记录
     * @param id 心情记录ID
     * @param moodRecord 心情记录信息
     * @return 更新结果
     */
    @PutMapping("/mood-records/{id}")
    public ResponseEntity<Map<String, Object>> updateMoodRecord(@PathVariable Long id, @RequestBody MoodRecord moodRecord) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            MoodRecord existing = moodRecordService.getById(id);
            if (existing == null) {
                response.put("success", false);
                response.put("message", "心情记录不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            moodRecord.setId(id);
            moodRecord.setCreateTime(existing.getCreateTime());
            boolean success = moodRecordService.updateMoodRecord(moodRecord);
            
            if (success) {
                response.put("success", true);
                response.put("message", "心情记录更新成功");
                response.put("data", moodRecord);
            } else {
                response.put("success", false);
                response.put("message", "心情记录更新失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新心情记录失败", e);
            response.put("success", false);
            response.put("message", "更新心情记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 删除心情记录
     * @param id 心情记录ID
     * @return 删除结果
     */
    @DeleteMapping("/mood-records/{id}")
    public ResponseEntity<Map<String, Object>> deleteMoodRecord(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            MoodRecord existing = moodRecordService.getById(id);
            if (existing == null) {
                response.put("success", false);
                response.put("message", "心情记录不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            boolean success = moodRecordService.deleteMoodRecord(id);
            
            if (success) {
                response.put("success", true);
                response.put("message", "心情记录删除成功");
            } else {
                response.put("success", false);
                response.put("message", "心情记录删除失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除心情记录失败", e);
            response.put("success", false);
            response.put("message", "删除心情记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取心情记录详情
     * @param id 心情记录ID
     * @return 心情记录信息
     */
    @GetMapping("/mood-records/{id}")
    public ResponseEntity<Map<String, Object>> getMoodRecord(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            MoodRecord moodRecord = moodRecordService.getById(id);
            if (moodRecord == null) {
                response.put("success", false);
                response.put("message", "心情记录不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            response.put("success", true);
            response.put("message", "获取心情记录成功");
            response.put("data", moodRecord);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取心情记录失败", e);
            response.put("success", false);
            response.put("message", "获取心情记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 分页查询心情记录列表
     * @param page 页码
     * @param size 每页大小
     * @param userId 用户ID（必需）
     * @param moodType 心情类型（可选）
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @param shared 是否只查询分享的记录（可选）
     * @return 心情记录列表
     */
    @GetMapping("/mood-records")
    public ResponseEntity<Map<String, Object>> getMoodRecordList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam Long userId,
            @RequestParam(required = false) String moodType,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) Boolean shared) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Page<MoodRecord> pageRequest = new Page<>(page, size);
            IPage<MoodRecord> moodRecordPage;
            
            if (shared != null && shared) {
                // 查询分享的心情记录
                moodRecordPage = moodRecordService.findSharedByUserId(userId, pageRequest);
            } else if (moodType != null) {
                // 按心情类型查询
                moodRecordPage = moodRecordService.findByUserIdAndMoodType(userId, moodType, pageRequest);
            } else if (startTime != null && endTime != null) {
                // 按时间范围查询
                LocalDateTime start = LocalDateTime.parse(startTime);
                LocalDateTime end = LocalDateTime.parse(endTime);
                moodRecordPage = moodRecordService.findByUserIdAndTimeRange(userId, start, end, pageRequest);
            } else {
                // 查询用户所有心情记录
                moodRecordPage = moodRecordService.findByUserId(userId, pageRequest);
            }
            
            response.put("success", true);
            response.put("message", "获取心情记录列表成功");
            response.put("data", moodRecordPage.getRecords());
            response.put("total", moodRecordPage.getTotal());
            response.put("pages", moodRecordPage.getPages());
            response.put("current", moodRecordPage.getCurrent());
            response.put("size", moodRecordPage.getSize());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取心情记录列表失败", e);
            response.put("success", false);
            response.put("message", "获取心情记录列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取用户最近的心情记录
     * @param userId 用户ID
     * @param limit 限制数量（默认10）
     * @return 最近的心情记录列表
     */
    @GetMapping("/mood-records/recent")
    public ResponseEntity<Map<String, Object>> getRecentMoodRecords(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "10") Integer limit) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<MoodRecord> moodRecords = moodRecordService.findRecentByUserId(userId, limit);
            
            response.put("success", true);
            response.put("message", "获取最近心情记录成功");
            response.put("data", moodRecords);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取最近心情记录失败", e);
            response.put("success", false);
            response.put("message", "获取最近心情记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取用户今日心情记录
     * @param userId 用户ID
     * @return 今日心情记录列表
     */
    @GetMapping("/mood-records/today")
    public ResponseEntity<Map<String, Object>> getTodayMoodRecords(@RequestParam Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<MoodRecord> moodRecords = moodRecordService.findTodayByUserId(userId);
            
            response.put("success", true);
            response.put("message", "获取今日心情记录成功");
            response.put("data", moodRecords);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取今日心情记录失败", e);
            response.put("success", false);
            response.put("message", "获取今日心情记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 统计用户心情记录数量
     * @param userId 用户ID
     * @return 心情记录统计信息
     */
    @GetMapping("/mood-records/stats")
    public ResponseEntity<Map<String, Object>> getMoodRecordStats(@RequestParam Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long totalCount = moodRecordService.countByUserId(userId);
            List<MoodRecord> todayRecords = moodRecordService.findTodayByUserId(userId);
            
            response.put("success", true);
            response.put("message", "获取心情记录统计成功");
            response.put("data", Map.of(
                "totalCount", totalCount,
                "todayCount", todayRecords.size()
            ));
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取心情记录统计失败", e);
            response.put("success", false);
            response.put("message", "获取心情记录统计失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}